// middleware/checkPermission.js
const pool = require('../db');

const checkPermission = (requiredPermission) => {
  return async (req, res, next) => {
    try {
      const [userRows] = await pool.query('SELECT * FROM Users WHERE id = ?', [req.user.id]);
      if (userRows.length === 0) {
        return res.status(404).json({ message: 'User not found' });
      }

      const [roleRows] = await pool.query(`
        SELECT Roles.id, Roles.name, Permissions.name as permission_name
        FROM UserRoles
        JOIN Roles ON UserRoles.role_id = Roles.id
        JOIN RolePermissions ON Roles.id = RolePermissions.role_id
        JOIN Permissions ON RolePermissions.permission_id = Permissions.id
        WHERE UserRoles.user_id = ?
      `, [req.user.id]);

      const userPermissions = roleRows.map(role => role.permission_name);

      if (userPermissions.includes(requiredPermission)) {
        return next();
      } else {
        return res.status(403).json({ message: 'Permission denied' });
      }
    } catch (error) {
      return res.status(500).json({ message: 'Internal server error' });
    }
  };
};

module.exports = checkPermission;